package com.example.ex_jd.service;

import com.alibaba.fastjson.JSON;
import com.example.ex_jd.pojo.Content;
import com.example.ex_jd.utils.HtmlParseUtil;
import org.elasticsearch.action.bulk.BulkRequest;
import org.elasticsearch.action.bulk.BulkResponse;
import org.elasticsearch.action.index.IndexRequest;
import org.elasticsearch.action.search.SearchRequest;
import org.elasticsearch.action.search.SearchResponse;
import org.elasticsearch.client.RequestOptions;
import org.elasticsearch.client.RestHighLevelClient;
import org.elasticsearch.common.text.Text;
import org.elasticsearch.common.unit.TimeValue;
import org.elasticsearch.common.xcontent.XContentType;
import org.elasticsearch.index.query.QueryBuilders;
import org.elasticsearch.index.query.TermQueryBuilder;
import org.elasticsearch.search.SearchHit;
import org.elasticsearch.search.builder.SearchSourceBuilder;
import org.elasticsearch.search.fetch.subphase.highlight.HighlightBuilder;
import org.elasticsearch.search.fetch.subphase.highlight.HighlightField;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.io.IOException;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import java.util.concurrent.TimeUnit;

/**
 * @author 77317
 * @Title: ContentService
 * @projectName ex_jd
 * @description: 业务编写
 * @date 2020/5/11 13:48
 * @Version V1.0
 */
@Service
public class ContentService {
    @Autowired
    private RestHighLevelClient restHighLevelClient;
    //不能直接使用@Autowired  只要spring容器
    public static void main(String[] args)  throws Exception{
        new ContentService().parseConten("java");
    }
    //1，解析数据放入es索引中
    public  Boolean parseConten(String keywords) throws Exception{
        List<Content> contents = new HtmlParseUtil().praresJd(keywords);
        BulkRequest bulkRequest = new BulkRequest();
        bulkRequest.timeout("2m");
        for (int i=0;i<contents.size();i++){
            bulkRequest.add(new IndexRequest("jd_goods")
            .source(JSON.toJSONString(contents.get(i)), XContentType.JSON));
        }
        BulkResponse bulk = restHighLevelClient.bulk(bulkRequest, RequestOptions.DEFAULT);
        return  !bulk.hasFailures();

    }
    //2,获取这些数据实现搜索功能
    public  List<Map<String,Object>> serachPage(String keyword,int pageNo,int pageSize) throws IOException {
        if(pageNo<=1){
            pageNo=1;
        }
        //条件搜索
        SearchRequest request = new SearchRequest("jd_goods");
        //构建器
        SearchSourceBuilder searchSourceBuilder = new SearchSourceBuilder();
        //分页
        searchSourceBuilder.from(pageNo);
        searchSourceBuilder.size(pageSize);

        //精准匹配
        TermQueryBuilder title = QueryBuilders.termQuery("title", keyword);
        searchSourceBuilder.query(title);
        //设置超时
        searchSourceBuilder.timeout(new TimeValue(60, TimeUnit.SECONDS));


        //执行搜索
        request.source(searchSourceBuilder);
        SearchResponse search = restHighLevelClient.search(request, RequestOptions.DEFAULT);
        //解析结果
        ArrayList<Map<String,Object>> objects = new ArrayList<>();
        for(SearchHit searchHit: search.getHits().getHits()){
            objects.add(searchHit.getSourceAsMap());
        }
        return  objects;
    }
    //3，获取这些数据实现搜索高亮功能
    public  List<Map<String,Object>> serachPageHighlighter(String keyword,int pageNo,int pageSize) throws IOException {
        if(pageNo<=1){
            pageNo=1;
        }
        //条件搜索
        SearchRequest request = new SearchRequest("jd_goods");
        //构建器
        SearchSourceBuilder searchSourceBuilder = new SearchSourceBuilder();
        //分页
        searchSourceBuilder.from(pageNo);
        searchSourceBuilder.size(pageSize);

        //精准匹配
        TermQueryBuilder title = QueryBuilders.termQuery("title", keyword);
        searchSourceBuilder.query(title);
        //设置超时
        searchSourceBuilder.timeout(new TimeValue(60, TimeUnit.SECONDS));
        //高亮
        HighlightBuilder highlightBuilder = new HighlightBuilder();
        highlightBuilder.field("title");//高亮的名字
        highlightBuilder.requireFieldMatch(false);//多个vue关闭
        highlightBuilder.preTags("<span style='color:red'>");//前缀
        highlightBuilder.postTags("</span>");//后缀
        searchSourceBuilder.highlighter(highlightBuilder);

        //执行搜索
        request.source(searchSourceBuilder);
        SearchResponse search = restHighLevelClient.search(request, RequestOptions.DEFAULT);
        //解析结果
        ArrayList<Map<String,Object>> objects = new ArrayList<>();
        for(SearchHit searchHit: search.getHits().getHits()){
            //解析高亮的字段
            Map<String, HighlightField> highlightFields = searchHit.getHighlightFields();
            HighlightField title1 = highlightFields.get("title");
            //取出原来的值
            Map<String, Object> sourceAsMap = searchHit.getSourceAsMap();
            if(title1!=null){
                //解析高亮字段，将原来字段替换高亮的字段
                Text[] fragments = title1.fragments();
                String n_title="";
                for (Text text:fragments){
                    n_title+=text;
                }
                sourceAsMap.put("title",n_title);//替换掉原来的内容
            }
            objects.add(searchHit.getSourceAsMap());
        }
        return  objects;
    }
}
